import traceback
import logging

from django.shortcuts import render

# Create your views here.
from django.db.models import Q
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework import generics, mixins, views
from django_nameko import get_pool
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from square.models import SquareDynamic, SquareComment
from square.serializers import SquareDynamicSerializer, SquareCommentSerializer

from common.utils import LargeResultsSetPagination
from common.custom_permission import IsCheckerPermission
from square.form_data import SquareForm

logger = logging.getLogger('log')
dynamic_logger = logging.getLogger('check_dynamic')


class AddSquareDynamic(generics.GenericAPIView):
    """
    创建广场动态
    """
    permission_classes = [permissions.IsAuthenticated]
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['content'], properties=
                                  {'content': openapi.Schema(type=openapi.TYPE_STRING, description='广场内容')}
                                  )

    @swagger_auto_schema(method='post', request_body=request_body, )
    @action(methods=['post'], detail=False, )
    def post(self, request):
        try:
            data = request.data
            result = SquareForm(data)
            logger.info('222222222{}'.format(result.is_valid()))
            if result.is_valid():
                result_data = result.cleaned_data
                content = data.get('content')
                # obj = SquareComment.objects.create(**result_data)
                # obj = SquareDynamic.objects.create(user=request.user, content=content)
                # obj.save()
                return Response({'code': 200, 'message': '发布广场动态成功'})
            else:
                error = result.errors
                logger.error('AddSquareDynamic errors:{}'.format(error))
                return Response({'code': 500, 'message': '数据异常'})
        except Exception as e:
            logger.error(e)
            return Response({'code': 500, 'message': '数据异常'})


class SearchDynamicList(generics.GenericAPIView):
    """
    获取广场动态
    """
    serializer_class = SquareDynamicSerializer

    permission_classes = [permissions.IsAuthenticated]
    query_param = [openapi.Parameter(name='q', in_=openapi.IN_QUERY, description="查询条件", type=openapi.TYPE_STRING),
                   openapi.Parameter(name='size', in_=openapi.IN_QUERY, description="页数大小", type=openapi.TYPE_NUMBER),
                   openapi.Parameter(name='page', in_=openapi.IN_QUERY, description="页码", type=openapi.TYPE_NUMBER),
                   openapi.Parameter(name='user_id', in_=openapi.IN_QUERY, description="用户id",
                                     type=openapi.TYPE_NUMBER),
                   ]

    @swagger_auto_schema(method='get', manual_parameters=query_param, )
    @action(methods=['get'], detail=False, )
    def get(self, request):
        data = request.query_params
        q = data.get('q')
        user_id = data.get('user_id')
        if user_id:
            result_list = SquareDynamic.objects.filter(user_id=user_id, status=2).order_by('-id')
        else:
            if not q:
                result_list = SquareDynamic.objects.filter(status=2).order_by('-id')
            else:
                result_list = SquareDynamic.objects.filter(content__icontains=q, status=2).order_by(
                    '-id')

        total_count = result_list.count()
        # 实例化分页对象
        page_cursor = LargeResultsSetPagination()
        # 分页
        data_list = page_cursor.paginate_queryset(result_list, request, view=self)

        data_list = self.get_serializer(data_list, many=True).data
        result = {'code': 200, 'data': data_list, 'total_count': total_count}
        return Response(result)


class AddDynamicComment(generics.GenericAPIView):
    """
    添加评论
    """
    permission_classes = [permissions.IsAuthenticated]
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT, required=['content'], properties=
    {'content': openapi.Schema(type=openapi.TYPE_STRING, description='评论内容'),
     'dynamic_id': openapi.Schema(type=openapi.TYPE_NUMBER, description='动态id'),
     'comment_id': openapi.Schema(type=openapi.TYPE_NUMBER, description='评论的id'),
     }
                                  )

    @swagger_auto_schema(method='post', request_body=request_body, )
    @action(methods=['post'], detail=False, )
    def post(self, request):
        data = request.data
        content = data.get('content')
        dynamic_id = data.get('dynamic_id')
        comment_id = data.get('comment_id')
        # 查找到对应的动态
        dynamic = SquareDynamic.objects.filter(id=dynamic_id).first()
        if not dynamic:
            return Response({'code': 406, 'message': '评论失败'})
        obj = SquareComment.objects.create(user=request.user, content=content, square_dynamic=dynamic)

        if comment_id:
            obj.parent_id = comment_id
        obj.save()
        return Response({'code': 200, 'message': '评论成功'})


class GetCommentList(generics.GenericAPIView):
    """
    获取评论列表
    """
    serializer_class = SquareCommentSerializer

    permission_classes = [permissions.IsAuthenticated]
    query_param = [
        openapi.Parameter(name='dynamic_id', in_=openapi.IN_QUERY, description="动态id", type=openapi.TYPE_NUMBER),
    ]

    @swagger_auto_schema(method='get', manual_parameters=query_param, )
    @action(methods=['get'], detail=False, )
    def get(self, request):
        data = request.query_params
        dynamic_id = data.get('dynamic_id')
        if not dynamic_id:
            return Response({'code': 406, 'message': '获取数据失败'})
        comment_list = SquareComment.objects.filter(square_dynamic_id=dynamic_id).order_by('-id')
        data = self.get_serializer(comment_list, many=True).data
        return Response({'code': 200, 'data': data})


class GetDynamicInfo(generics.GenericAPIView):
    """
    获取广场动态详细信息
    """
    serializer_class = SquareDynamicSerializer

    permission_classes = [permissions.IsAuthenticated]
    query_param = [
        openapi.Parameter(name='dynamic_id', in_=openapi.IN_QUERY, description="动态id", type=openapi.TYPE_STRING),
    ]

    @swagger_auto_schema(method='get', manual_parameters=query_param, )
    @action(methods=['get'], detail=False, )
    def get(self, request):
        data = request.query_params
        dynamic_id = data.get('dynamic_id')
        result = SquareDynamic.objects.filter(user_id=dynamic_id).first()

        data = self.get_serializer(result).data
        result = {'code': 200, 'data': data}
        return Response(result)


class UpdateDynamicStatus(generics.GenericAPIView):
    """
    更新动态状态
    """
    serializer_class = SquareDynamicSerializer

    permission_classes = [permissions.IsAdminUser, IsCheckerPermission]
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT, required=['content'],
                                  properties={'status': openapi.Schema(type=openapi.TYPE_STRING, description='status'),
                                              'dynamic_id': openapi.Schema(type=openapi.TYPE_NUMBER,
                                                                           description='动态id'),
                                              }
                                  )

    @swagger_auto_schema(method='post', request_body=request_body, )
    @action(methods=['post'], detail=False, )
    def post(self, request):
        data = request.data
        status = data.get('status')
        dynamic_id = data.get('dynamic_id')
        dynamic = SquareDynamic.objects.filter(id=dynamic_id).first()
        if not dynamic:
            return Response({'code': 407, 'message': '参数错误'})
        # TODO 增加审核的日志记录
        dynamic_logger.info('UpdateDynamicStatus[{}]: {} ----> {}'.format(dynamic_id, dynamic.status, status))
        dynamic.status = status
        dynamic.save()
        return Response({'code': 200, 'message': '审核完成'})
